package com.cindata

import grails.converters.JSON
import org.springframework.security.access.annotation.Secured

import grails.transaction.Transactional
import java.text.DecimalFormat
import java.text.SimpleDateFormat

@Secured(['isAuthenticated()'])
@Transactional
class BuildingsRatedController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def apiService
    def scoreApiService
    def searchApiService
    def dataSource

    /**
     * 页面数据回显
     * @return
     */
    def index()
    {

    }

    /**
     * 一级页面查询小区
     * @return
     */
    def searchBuilding()
    {

        def city = params['city']
        def cityName = City.findByZoneNumber(city)
        def keywords = params['keywords']
        def str = []
        def communityIds = []
        //获取小区列表
        def cityList = searchApiService.communitySearch(cityName.name, keywords, 5)
        println cityList
        int flag = 0
        cityList.each {
            if (it?.communityName)
            {
                str[flag] = it?.communityName ? it?.communityName : ""
                communityIds[flag] = it?.communityId ? it?.communityId : ""
                flag++
            }

        }

        render([s: str, city: city, id: communityIds] as JSON)
    }

    /**
     * 判断该小区是否有流动性评分*/
    def hasScore()
    {
        def communityId = params['id']
        def score = scoreApiService.communityLiquidityScore(communityId)
        render([score: score] as JSON)
    }

    /**
     * 获取12个月份字符串
     * @return
     */
    def getRecentDate()
    {
        StringBuffer rStr = new StringBuffer("");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM")
        Calendar ca = Calendar.getInstance()
        for (
            int i = -12;
                i <= -1;
                i++)
        {
            ca.setTime(new Date())
            ca.add(Calendar.MONTH, i)
            rStr.append(sdf.format(ca.getTime()) + ",")
        }
        return rStr.toString()
    }

    /**
     * 对数据进行处理，日期排序，数据不组进行补0
     * @param str
     * @return
     */
    def dealData(String str)
    {
        def tempData = []
        def tempDate = []
        def rdate = getRecentDate().split(",")
        if (str != "--" && str != null)
        {
            tempData = str.split(";")[0].split(",")
            tempDate = str.split(";")[1].split(",")

            //数据处理成map
            Map map = new HashMap<String, String>()
            int x = -1
            tempDate.each {
                x++
                map.put(tempDate[x], tempData[x])
            }
            int y = -1
            StringBuffer returnDate = new StringBuffer("")
            StringBuffer returnData = new StringBuffer("")
            rdate.each {
                y++
                Object obj = map.get(it)
                String temp = ","
                if (y == 11)
                {
                    temp = ""
                }
                if (obj)
                {
                    returnData.append(obj + temp)
                    returnDate.append(it + temp)
                }
                else
                {
                    returnData.append("0" + temp)
                    returnDate.append(it + temp)
                }
            }
            println "final:" + returnData + ";" + returnDate
            return returnData + ";" + returnDate
        }
        else
        {
            println "0,0,0,0,0,0,0,0,0,0,0,0;" + rdate
            return "0,0,0,0,0,0,0,0,0,0,0,0;" + rdate
        }

    }

    /**
     * 前往流通性评估页面*/
    def circulationAssessment()
    {
        def zoneNumber = params['city']
        def communityId = Long.parseLong(params['id'])
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //流动性评分
        def score = scoreApiService.communityLiquidityScore(communityId.toString())
        //小区价格走势
        def rate = apiService.communityRate(zoneNumber, communityId.toString())
        //获取上月数据
        def month = apiService.communityLastMonthData(zoneNumber, communityId.toString())
        //获取挂牌案例数量
        def listingCount = Integer.parseInt(month?.data?.netlistingNum ? month?.data?.netlistingNum : "0")
        //获取成交案例数量
        //暂时不用def saleCount =Integer.parseInt(month?.data?.saleNum ? month?.data?.saleNum : "0")
        def saleCount = 0
        //获取小区均价
        def averPrice = Double.parseDouble(month?.data?.price ? month?.data?.price : "0")
        println "score--" + score
        println "month--" + month
        println "rate--" + rate
        //小区1年内的小区价格走势
        def trendPriceCommunityData = []
        def trendPriceCommunityDate = []
        String trendPriceCommunityStr = dealData(rate?.code == "0" ? rate?.data?.trendPriceCommunity : "--")
        trendPriceCommunityData = trendPriceCommunityStr.split(";")[0].split(",").toString()
        trendPriceCommunityDate = trendPriceCommunityStr.split(";")[1].split(",").toString()

        //小区1年内的挂牌量趋势
        def trendNetlistData = []
        def trendNetlistDate = []
        String trendNetlistStr = dealData(rate?.code == "0" ? rate?.data?.trendNetlist : "--")
        trendNetlistData = trendNetlistStr.split(";")[0].split(",").toString()
        trendNetlistDate = trendNetlistStr.split(";")[1].split(",").toString()

        //小区1年内小区的交易量趋势
        def communityTrendSaleData = []
        def communityTrendSaleDate = []
        String communityTrendSaleStr = dealData(rate?.code == "0" ? rate?.data?.communityTrendSale : "--")
        communityTrendSaleData = communityTrendSaleStr.split(";")[0].split(",").toString()
        communityTrendSaleDate = communityTrendSaleStr.split(";")[1].split(",").toString()

        int f = 0;
        communityTrendSaleData.replace("[", "").replace("]", "").replace(" ", "").split(",").each {
            if (f >= 6)
            {
                println it
                saleCount = saleCount + Integer.parseInt(it);
            }
            f++
        }
        //查询权值
        def communityScoreWeight = CommunityScoreWeight.list().get(0)



        def closingWeight = communityScoreWeight.closingWeight
        // 成交率权重
        def listingWeight = communityScoreWeight.listingWeight
        // 挂牌率权重
        def dealAvgDayWeight = communityScoreWeight.dealAvgDayWeight
        // 成交周期权重
        def discountrateWeight = communityScoreWeight.discountrateWeight
        // 折价比权重
        def foreclosureTimesWeight = communityScoreWeight.foreclosureTimesWeight
        // 法拍次数权重

        //小区配套权值
        def ifSchoolZoneScoreWeight = communityScoreWeight.schoolDistrictsWeight
        def communityTrafficScoreWeight = communityScoreWeight.trafficWeight
        def houseAgeScoreWeight = communityScoreWeight.houseAgeWeight
        def communityHospitalScoreWeight = communityScoreWeight.hospitalWeight
        def communityMallScoreWeight = communityScoreWeight.mallWeight
        def communityGreeningrateScoreWeight = communityScoreWeight.afforestationWeight
        def communityPlotratioScoreWeight = communityScoreWeight.ratioWeight
        def communityParkScoreWeight = communityScoreWeight.parkWeight
        def communityPmfeeScoreWeight = communityScoreWeight.propertyFeeWeight
        def communitySupermarketScoreWeight = communityScoreWeight.superMarketWeight
        def communityBankScoreWeight = communityScoreWeight.bankWeight

        def scenicWeight = communityScoreWeight.scenicWeight
        def noisePullutionWeight = communityScoreWeight.noisePullutionWeight
        def airPullutionWeight = communityScoreWeight.airPullutionWeight

        //小区总分
        def liquidWeight = communityScoreWeight.liquidityWeight
        def surroundWeight = communityScoreWeight.assortWeight
        def natureWeight = communityScoreWeight.natureWeight

        //小区配套评分
        def ifSchoolZoneScore = 0
        def communityTrafficScore = 0
        def houseAgeScore = 0
        def communityHospitalScore = 0
        def communityMallScore = 0
        def communityGreeningrateScore = 0
        def communityPlotratioScore = 0
        def communityParkScore = 0
        def communityPmfeeScore = 0
        def communitySupermarketScore = 0
        def communityBankScore = 0

        //流动性评分
        def closingScore = 0
        def dealAvgDayScore = 0
        def listingScore = 0
        def discountrateScore = 0
        def foreclosureTimesScore = 0

        def scenicScore = 0
        def noisePullutionScore = 0
        def airPullutionScore = 0

        //小区配套总分
        def communitySurroundingScore = 0

        //小区流动性总分
        def liquidityScore = 0

        //小区自然总分
        def natureScore = 0

        def scoreArr = []
        def surroudArr = []
        def natureArr = []

        DecimalFormat df = new DecimalFormat("#.00");
        DecimalFormat df1 = new DecimalFormat("#.0");
        if (score?.closingScore)
        {
            //成交率评分
            closingScore = (score?.closingScore ? score?.closingScore : 0) * closingWeight
            //成交周期评分
            dealAvgDayScore = (score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) * dealAvgDayWeight
            //挂牌率评分
            listingScore = (score?.listingScore ? score?.listingScore : 0) * listingWeight
            //折价比例评分（法拍计算）
            discountrateScore = (score?.discountrateScore ? score?.discountrateScore : 0) * discountrateWeight
            //法拍次数评分
            foreclosureTimesScore = (score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) * foreclosureTimesWeight

            ifSchoolZoneScore = (score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) * ifSchoolZoneScoreWeight
            communityTrafficScore = (score?.communityTrafficScore ? score?.communityTrafficScore : 0) * communityTrafficScoreWeight
            houseAgeScore = (score?.houseAgeScore ? score?.houseAgeScore : 0) * houseAgeScoreWeight
            communityHospitalScore = (score?.communityHospitalScore ? score?.communityHospitalScore : 0) * communityHospitalScoreWeight
            communityMallScore = (score?.communityMallScore ? score?.communityMallScore : 0) * communityMallScoreWeight
            communityGreeningrateScore = (score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) * communityGreeningrateScoreWeight
            communityPlotratioScore = (score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) * communityPlotratioScoreWeight
            communityParkScore = (score?.communityParkScore ? score?.communityParkScore : 0) * communityParkScoreWeight
            communityPmfeeScore = (score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) * communityPmfeeScoreWeight
            communitySupermarketScore = (score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) * communitySupermarketScoreWeight
            communityBankScore = (score?.communityBankScore ? score?.communityBankScore : 0) * communityBankScoreWeight

            scenicScore = (score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) * scenicWeight
            noisePullutionScore = (score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) * noisePullutionWeight
            airPullutionScore = (score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) * airPullutionWeight

            communitySurroundingScore = ifSchoolZoneScore + communityTrafficScore + houseAgeScore + communityHospitalScore + communityMallScore + communityGreeningrateScore + communityPlotratioScore + communityParkScore + communityPmfeeScore + communitySupermarketScore + communityBankScore

            liquidityScore = closingScore + dealAvgDayScore + listingScore + discountrateScore + foreclosureTimesScore

            natureScore = scenicScore + noisePullutionScore + airPullutionScore

            scoreArr = "[" + df.format(score?.closingScore ? score?.closingScore : 0) + "," + df.format(score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) + "," + df.format(score?.listingScore ? score?.listingScore : 0) + "," + df.format(score?.discountrateScore ? score?.discountrateScore : 0) + "," + df.format(score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) + "]"
            surroudArr = "[" + df.format(score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) + "," + df.format(score?.communityTrafficScore ? score?.communityTrafficScore : 0) + "," + df.format(score?.houseAgeScore ? score?.houseAgeScore : 0) + "," + df.format(score?.communityHospitalScore ? score?.communityHospitalScore : 0) + "," + df.format(score?.communityMallScore ? score?.communityMallScore : 0) + "," + df.format(score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) + "," + df.format(score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) + "," + df.format(score?.communityParkScore ? score?.communityParkScore : 0) + "," + df.format(score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) + "," + df.format(score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) + "," + df.format(score?.communityBankScore ? score?.communityBankScore : 0) + "]"
            natureArr = "[" + df.format(score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) + "," + df.format(score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) + "," + df.format(score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) + "]"
            println surroudArr
        }


        def communityScore = liquidityScore * liquidWeight + communitySurroundingScore * surroundWeight + natureScore * natureWeight

        //查询所有押品数量
        def estateCount = Estate.countByCommunityId(communityId)

        //计算押品均价
        def estateList = Estate.findAllByCommunityId(communityId)

        def totalUnitPrice = 0
        def sumLoansBalance = 0
        def sumLoansEvaluatePrice = 0
        def avgUnitPrice = 0
        def avgCltv = 0
        estateList.each {
            totalUnitPrice += it.unitPrice ? it.unitPrice : 0
            sumLoansBalance += it.loansBalance ? it.loansBalance : 0
            sumLoansEvaluatePrice += it.loansEvaluateTotalPrice ? it.loansEvaluateTotalPrice : 0
        }

        if (estateList)
        {
            //押品均价
            avgUnitPrice = totalUnitPrice / estateList.size()
            //动态抵押率
            avgCltv = sumLoansBalance / sumLoansEvaluatePrice
        }
        //成交周期
        def saleCycle = score?.dealAverageDay
        respond liquidityScore,
                model: [liquidityScore: df1.format(liquidityScore),
                    communitySurroundingScore: df1.format(communitySurroundingScore),
                    natureScore:df1.format(natureScore),
                    communityScore: df1.format(communityScore),
                    communityId: communityId,
                    scoreArr: scoreArr,
                    surroudArr: surroudArr,
                    natureArr:natureArr,
                    community: community?.data,
                    estateCount: estateCount,
                    avgUnitPrice: avgUnitPrice,
                    avgCltv: avgCltv,
                    listingCount: listingCount,
                    saleCount: saleCount,
                    saleCycle: saleCycle,
                    averPrice: averPrice,
                    trendPriceCommunityData: trendPriceCommunityData,
                    trendPriceCommunityDate: trendPriceCommunityDate,
                    trendNetlistData: trendNetlistData,
                    trendNetlistDate: trendNetlistDate,
                    communityTrendSaleData: communityTrendSaleData,
                    communityTrendSaleDate: communityTrendSaleDate,
                    score: score], view: "circulationAssessment"
    }
}